package com.lanou.horo.zhuizhui.utility.imageLoader;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;


/**
 * Created by Risky on 15/10/21.
 */
public class VolleySingleton {
    private static VolleySingleton instance;
    private RequestQueue queue;
    private ImageLoader imageLoader;

    private VolleySingleton() {
        queue = getQueue();
        imageLoader = new ImageLoader(queue, new DoubleCache());
    }
//    public static VolleySingleton getInstance(){
//        return instance;
//    }
    public static VolleySingleton getInstance(){
        if (instance == null) {
            synchronized (VolleySingleton.class){
                if (instance == null) {
                    instance = new VolleySingleton();
                }
            }
        }
        return instance;
    }

    private RequestQueue getQueue(){
        if (queue == null) {
            queue = Volley.newRequestQueue(BaseApplication.getContext());
        }
        return queue;
    }
    public static final String TAG = "VolleySingleton";

    public <T> void addRequest(Request<T> request){
        request.setTag(TAG);
        queue.add(request);
    }

    public <T> void addRequest(Request<T> request,Object tag){
        request.setTag(tag);
        queue.add(request);
    }

    public void addStringRequest(String url,Response.Listener listener,
                                 Response.ErrorListener error){
        StringRequest stringRequest = new StringRequest(url,listener,error);
        addRequest(stringRequest);

    }

    public void removeRequest(Object tag){
        queue.cancelAll(tag);
    }

    public ImageLoader getImageLoader() {
        return imageLoader;
    }
}
